package com.homework.controller;

import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.databind.ser.Serializers;
import com.homework.content.BaseContext;
import com.homework.dto.HomeworkDto;
import com.homework.dto.StudentDto;
import com.homework.entity.*;
import com.homework.pojo.Result;
import com.homework.service.*;
import com.homework.vo.AssignmentVo;
import com.homework.vo.TeacherVo;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping("student")
public class StudentController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private AssignmentService assignmentService;
    @Autowired
    private StudentAssignmentService studentAssignmentService;
    @Autowired
    private StudentTeacherService studentTeacherService;

    /**
     * 获取学生个人信息
     *
     * @return
     */
    @GetMapping("my")
    public Result my() {
        return Result.success(studentService.getById(BaseContext.getCurrentId()));
    }

    /**
     * 修改个人信息
     *
     * @param studentDto
     * @return
     */
    @PutMapping("my")
    public Result my(@RequestBody @Valid StudentDto studentDto) {
        Long userId = BaseContext.getCurrentId();
        Student one = studentService.lambdaQuery()
                .eq(Student::getStudentId, userId)
                .one();
        if (one == null)
            return Result.error("用户不存在");
        BeanUtils.copyProperties(studentDto, one);
        one.setPassword(MD5.create().digestHex16(one.getPassword()));
        studentService.updateById(one);
        return Result.success();
    }

    /**
     * 添加老师
     *
     * @param id           老师id
     * @param relationship 与老师的关系
     * @return
     */
    @PutMapping("/addTeacher/{id}")
    public Result addTeacher(@PathVariable String id, @RequestParam String relationship) {
        Long studentId = BaseContext.getCurrentId();
        StudentTeacher one = studentTeacherService.lambdaQuery()
                .eq(StudentTeacher::getStudentId, studentId)
                .eq(StudentTeacher::getTeacherId, id)
                .one();
        if (one != null)
            return Result.error("已添加过该老师");

        Teacher one1 = teacherService.lambdaQuery()
                .eq(Teacher::getTeacherNo, id)
                .one();
        StudentTeacher studentTeacher = new StudentTeacher();
        studentTeacher.setStudentId(studentId.intValue());
        studentTeacher.setTeacherId(one1.getTeacherId());
        studentTeacher.setRelationshipType(relationship);
        studentTeacherService.save(studentTeacher);
        return Result.success();
    }

    /**
     * 获取我的老师们的信息
     *
     * @return
     */
    @GetMapping("myTeacher")
    public Result myTeacher() {
        Long studentId = BaseContext.getCurrentId();
        return Result.success(studentTeacherService.lambdaQuery()
                .eq(StudentTeacher::getStudentId, studentId)
                .list().stream().map(studentTeacher -> {
                    Teacher byId = teacherService.getById(studentTeacher.getTeacherId());
                    TeacherVo teacherVo = new TeacherVo();
                    teacherVo.setDepartment(byId.getDepartment());
                    teacherVo.setName(byId.getName());
                    teacherVo.setRelationshipType(studentTeacher.getRelationshipType());
                    return teacherVo;
                }).toList());
    }

    /**
     * 获取未提交的作业信息
     *
     * @return
     */
    @GetMapping("homework")
    public Result homework() {
        return studentAssignmentService.homework();
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        File file1 = new File("D:\\upload\\");
        if (!file1.exists()) {
            file1.mkdirs();
        }
        String string = UUID.randomUUID().toString();
        String[] split = originalFilename.split("\\.");

        String path = string + "." + split[split.length - 1];

        File file2 = new File("D:\\upload\\" + path);
        file.transferTo(file2);
        return Result.success(path);
    }

    /**
     * 提交作业
     *
     * @param homeworkDto
     * @return
     */
    @PostMapping("homework")
    public Result homework(@RequestBody @Valid HomeworkDto homeworkDto) {
        Long userId = BaseContext.getCurrentId();
        StudentAssignment one = studentAssignmentService.lambdaQuery()
                .eq(StudentAssignment::getStudentId, userId)
                .eq(StudentAssignment::getAssignmentId, homeworkDto.getAssignmentId())
                .one();
        if (one != null)
            return Result.error("已提交过该作业");
        Assignment one1 = assignmentService.lambdaQuery()
                .eq(Assignment::getAssignmentId, homeworkDto.getAssignmentId())
                .one();
        if (one1 == null)
            return Result.error("作业不存在");
        Date now = new Date();
        if (now.after(one1.getDueDate()))
            return Result.error("已超过截止日期");
        StudentAssignment studentAssignment = new StudentAssignment();
        studentAssignment.setStudentId(userId.intValue());
        studentAssignment.setAssignmentId(homeworkDto.getAssignmentId());
        studentAssignment.setFilePath(homeworkDto.getFilePath());
        studentAssignment.setSubmitDate(new Date());
        studentAssignmentService.save(studentAssignment);
        return Result.success();
    }

    /**
     * 获取已提交的作业
     *
     * @return
     */
    @GetMapping("history")
    public Result history() {
        Long userId = BaseContext.getCurrentId();
        return Result.success(studentAssignmentService.lambdaQuery()
                .eq(StudentAssignment::getStudentId, userId)
                .list().stream()
                .map(studentAssignment -> {
                    AssignmentVo assignmentVo = new AssignmentVo();
                    Assignment one = assignmentService.lambdaQuery()
                            .eq(Assignment::getAssignmentId, studentAssignment.getAssignmentId())
                            .one();
                    BeanUtils.copyProperties(one, assignmentVo);
                    BeanUtils.copyProperties(studentAssignment, assignmentVo);
                    return assignmentVo;
                }).toList()
        );
    }
}
